package faf.web.data;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class NewAccountFormValidator implements Validator {

	@Override
	public boolean supports(Class clazz) {
		return NewAccountForm.class.equals(clazz);
	}

	@Override
	public void validate(Object command, Errors errors) {
		if (command == null) {
			errors.rejectValue("email", "value-required");
			return;
		}
		NewAccountForm newAccountForm = (NewAccountForm) command;
		
		String firstname = newAccountForm.getFirstname();
		firstname = firstname.trim();
		if(firstname.length()==0) {
			errors.rejectValue("firstname", "value-required");
		}
		
		String lastname = newAccountForm.getLastname();
		lastname = lastname.trim();
		if(lastname.length()==0) {
			errors.rejectValue("lastname", "value-required");
		}
		
		String email = newAccountForm.getEmail();
		email = email.trim();
		if(email.length()==0) {
			errors.rejectValue("email", "value-required");
		}

		
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher m = p.matcher(email);
		boolean matchFound = m.matches();
		
		
		
		if(newAccountForm.getPassword().length()<8) {
			errors.rejectValue("password", "password-invalid");
		}
		
		if(!newAccountForm.getPassword().equals(newAccountForm.getPassword2())) {
			errors.rejectValue("password2", "password-match");
		}
		
		if(!matchFound) {
			errors.rejectValue("email", "email-invalid");
			return;
		}
	}
}
